//
//  GMPerfectInfoVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/7/16.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMPerfectInfoVC.h"
#import "XZAddressVC.h"
@interface GMPerfectInfoVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
/**用户头像*/
@property (weak, nonatomic) IBOutlet UIImageView *userImg;
/**用户名*/
@property (weak, nonatomic) IBOutlet UILabel *userName;
/**用户姓名*/
@property (weak, nonatomic) IBOutlet UILabel *name;
/**用户性别*/
@property (weak, nonatomic) IBOutlet UILabel *useSex;
/**用户地区*/
@property (weak, nonatomic) IBOutlet UILabel *userAddress;

@end

@implementation GMPerfectInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"完善个人信息";
}
/**保存并登录按钮*/
- (IBAction)makeSureBtnClick:(id)sender {
     [self.navigationController popToRootViewControllerAnimated:YES];
}
/**用户名点击事件*/
- (IBAction)userNameTap:(id)sender {
    //创建一个弹框
    UIAlertController *addAlertVC = [UIAlertController alertControllerWithTitle:@"请输入您的用户名" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    //创建两个textFiled输入框
    [addAlertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入用户名";
    }];
    //创建取消事件(按钮)
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    //添加 取消事件 到 弹窗界面
    [addAlertVC addAction:cancelAction];
    //创建 确认按钮(事件) 并添加到弹窗界面
    __weak typeof(self) weakSelf= self;
    UIAlertAction *confirmAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        NSString *loginName = addAlertVC.textFields.firstObject.text;
        weakSelf.userName.text = loginName;
        [weakSelf updateUserInfo:@"LoginName" fieldValue:loginName];
    }];
    [addAlertVC addAction:confirmAction];
    //模态显示一个弹框  注意: UIAlterController只能通过模态形式进行弹出,不能使用push
    [self.navigationController presentViewController:addAlertVC animated:NO completion:nil];
}
/**用户姓名点击事件*/
- (IBAction)nameTap:(id)sender {
    //创建一个弹框
    UIAlertController *addAlertVC = [UIAlertController alertControllerWithTitle:@"请输入您的姓名" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    //创建两个textFiled输入框
    [addAlertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入姓名";
    }];
    //创建取消事件(按钮)
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    //添加 取消事件 到 弹窗界面
    [addAlertVC addAction:cancelAction];
    //创建 确认按钮(事件) 并添加到弹窗界面
    __weak typeof(self) weakSelf= self;
    UIAlertAction *confirmAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
         NSString *name = addAlertVC.textFields.firstObject.text;
       weakSelf.name.text = name;
        [weakSelf updateUserInfo:@"Name" fieldValue:name];
        
    }];
    [addAlertVC addAction:confirmAction];
    //模态显示一个弹框  注意: UIAlterController只能通过模态形式进行弹出,不能使用push
    [self.navigationController presentViewController:addAlertVC animated:NO completion:nil];
}
/**用户性别点击事件*/
- (IBAction)sexTap:(id)sender {
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"请选择性别"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             XZLog(@"action = %@", action);
                                                         }];
    UIAlertAction* manAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {
                                                          //响应事件
                                                          self.useSex.text = action.title;
                                                          [self updateUserInfo:@"Sex" fieldValue:action.title];
                                                      }];
    UIAlertAction* womanAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault
                                                        handler:^(UIAlertAction * action) {
                                                            //响应事件
                                                             self.useSex.text = action.title;
                                                            [self updateUserInfo:@"Sex" fieldValue:action.title];
                                                        }];
    [alert addAction:cancelAction];
    [alert addAction:manAction];
    [alert addAction:womanAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}
/**用户地区点击事件*/
- (IBAction)addressTap:(id)sender {
    kWeakObject(self)
    XZAddressVC *addressVC = [[XZAddressVC alloc]init];
    addressVC.type = @"UNSCUCESS";
    addressVC.AddressBlock = ^(NSString * _Nonnull address) {
        weakself.userAddress.text = address;
    };
    [self.navigationController pushViewController:addressVC animated:true];
}

/**用户头像点击事件*/
- (IBAction)userImgTap:(id)sender {
    [self updateUserImageView];
}

//上传头像
- (void)updateUserImageView{
    //显示弹出框列表选择
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"action = %@", action);
                                                         }];
    UIAlertAction* manAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {
                                                          [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypeCamera];
                                                      }];
    UIAlertAction* womanAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault
                                                        handler:^(UIAlertAction * action) {
                                                            //响应事件
                                                            [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
                                                        }];
    [alert addAction:cancelAction];
    [alert addAction:manAction];
    [alert addAction:womanAction];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate =self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing =YES;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
#pragma mark 选择照片上传服务器
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    [arr addObject:image];
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString * str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"fileType":@"user-head"
                          };
    [MBProgressHUD showErrorOrSuc:@"正在上传" toView:self.view];
    kWeakObject(self)
    [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/do-api.ashx?$m=UploadFile&$v=%@",VERSION] parameters:dict images:arr name:@"file" fileName:fileName mimeType:@"image/jpeg" progress:^(NSProgress *progress) {
        
    } callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                [MBProgressHUD showErrorOrSuc:@"上传成功" toView:weakself.view];
                NSDictionary *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                weakself.userImg.image = image;
                NSString *FileUrl = dataInfo[@"FileUrl"];
                //更新用户头像
                [weakself updateUserInfo:@"HeadUrl" fieldValue:FileUrl];
            }else{
                /**显示错误信息*/
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }
    }];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
/**
 更新用户信息

 @param fieldName 数据名称
 @param fieldValue 数据值
 */
- (void)updateUserInfo:(NSString *)fieldName fieldValue:(NSString *)fieldValue{
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                           @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"newUserId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"fieldName":fieldName,
                          @"fieldValue":fieldValue
                          };
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/do-api.ashx?$m=UpdateUserInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
               
                
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
    
}
@end
